package com.zqc.task;

import com.zqc.filter.TPMonitorFilter;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 上报线程任务
 */
public class ReportTask implements Runnable {
    private static final double PERCENT_90 = 0.9;
    private static final double PERCENT_99 = 0.99;

    @Override
    public void run() {
        System.out.println(LocalDateTime.now() + "开始上报...");
        Map<String, TreeSet<TPMonitorFilter.DimTime>> requestMap = TPMonitorFilter.REQUEST_MAP;
        if (requestMap != null && !requestMap.isEmpty()) {
            Set<Map.Entry<String, TreeSet<TPMonitorFilter.DimTime>>> entries = requestMap.entrySet();
            for (Map.Entry<String, TreeSet<TPMonitorFilter.DimTime>> entry : entries) {
                String key = entry.getKey();
                TreeSet<TPMonitorFilter.DimTime> value = entry.getValue();
                report(key, value);
            }
        }

        System.out.println("================================================================");
    }

    /**
     * 上报
     * @param key
     * @param value
     */
    private void report(String key, TreeSet<TPMonitorFilter.DimTime> value) {
        synchronized (value) {
            // 一分钟前的时间
            long beforeOneMinute = System.currentTimeMillis() - 60 * 1000;

            // 排除比一分钟前还之前的数据
            for (TPMonitorFilter.DimTime dimTime : value) {
                Long startTime = dimTime.getStartTime();
                if (startTime < beforeOneMinute) {
                    value.remove(dimTime);
                }
            }

            int size = value.size();
            int percent90 = (int) (size * PERCENT_90);
            int percent99 = (int) (size * PERCENT_99);

            // TP99就是满足百分之九十九的网络请求所需要的最低耗时
            // TP90就是满足百分之九十的网络请求所需要的最低耗时
            TPMonitorFilter.DimTime percent90Data = null;
            TPMonitorFilter.DimTime percent99Data = null;
            int counter = 1;
            for (TPMonitorFilter.DimTime dimTime : value) {
                if (counter == percent90) {
                    percent90Data = dimTime;
                } else if (counter == percent99) {
                    percent99Data = dimTime;
                }
                counter++;
            }
            System.out.println("服务【" + key + "】最近一分钟运行结果：");
            System.out.println("  90分位点耗时：" + percent90Data.getSpendTime());
            System.out.println("  99分位点耗时：" + percent99Data.getSpendTime());
        }
    }
}
